package 面试代码.线程顺序打印面试版;

/**
 * 方式二：synchronized + wait() + notify()
 */
public class Test2 {
    //锁住的对象
    private final static Object lock = new Object();
    //A是否已经执行过
    private static boolean aExecuted = false;
    //B是否已经执行过
    private static boolean bExecuted = false;
    public static void main(String[] args) {
        Thread t1 = new Thread(){
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("A");
                    aExecuted = true;
                    //唤醒所有等待线程
                    lock.notifyAll();
                }
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                synchronized (lock) {
                    //获取到锁，但是要等A执行
                    while (!aExecuted) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("B");
                    bExecuted = true;
                    lock.notifyAll();
                }
            }
        };
        Thread t3 = new Thread(){
            @Override
            public void run() {
                synchronized (lock) {
                    //获取到锁，但是要等B执行
                    while (!bExecuted) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("C");
                }
            }
        };
        t2.start();
        t1.start();
        t3.start();
    }
}